//
//  AppDelegate.m
//  iBeacon
//
//  Created by Apple on 12/18/15.
//  Copyright © 2015 Apple. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>

@interface AppDelegate ()<CLLocationManagerDelegate>
{
    CGFloat f;
    CGFloat m;
    CLLocationManager *locationManager;
    NSMutableArray *array;
    CLLocation *location;
}

@property (nonatomic) UIBackgroundTaskIdentifier taskId;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //NSLocationWhenInUseUsageDescription
    // Override point for customization after application launch.
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
    array=[NSMutableArray array];
    //create new CLLocationManager
    if ([CLLocationManager locationServicesEnabled]) {
        locationManager = [[CLLocationManager alloc] init];
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
            [locationManager requestAlwaysAuthorization];
        }
        locationManager.delegate = self;
        locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        locationManager.distanceFilter=kCLDistanceFilterNone;
        locationManager.pausesLocationUpdatesAutomatically=NO;
        
        
    }
    //    CLLocationDistance distance = 500;
    //    NSTimeInterval time = 20;
     //   [locationManager allowDeferredLocationUpdatesUntilTraveled:distance
    //                                                       timeout:time];
    
    
    return YES;
}



-(void)time{
    NSLog(@"%f",m++);
    NSLog(@"%f",f++);
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Only VoIP apps can set KeepAliveTimeout
    //    BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
    
   // [locationManager startUpdatingLocation];
    
    [self beginNewBackgroundTask];
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });
}

-(void)beginNewBackgroundTask{
    __block UIBackgroundTaskIdentifier bgTaskId_block = UIBackgroundTaskInvalid;
    UIApplication* application = [UIApplication sharedApplication];
    
    bgTaskId_block = [application beginBackgroundTaskWithExpirationHandler:^(void) {
        if(array.count==2){
            UIBackgroundTaskIdentifier bgTaskId = [[array objectAtIndex:0] integerValue];
            NSLog(@"现在的标志符为--------%ld",(unsigned long)bgTaskId);
            [application endBackgroundTask:bgTaskId];
            [array removeObjectAtIndex:0];
        }
    }];
    if(self.taskId==UIBackgroundTaskInvalid){
        self.taskId=bgTaskId_block;
    }else{
        f=0;
    }
    if(bgTaskId_block!=UIBackgroundTaskInvalid)
        [array addObject:@(bgTaskId_block)];
}


//starts automatically with locationManager
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    location=newLocation;
    NSLog(@"Location: %f, %f", newLocation.coordinate.longitude, newLocation.coordinate.latitude);
    //60秒开启一个新的,数组存放只存放两个标志
    if(f>=60&&array.count<2){
        [self beginNewBackgroundTask];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"%f",f);
    [locationManager stopUpdatingLocation];
    
    //[locationManager stopUpdatingLocation];
    UIAlertView *alter=[ [UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"精度为%f",location.altitude] message:[NSString stringWithFormat:@"时间为%f",f] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alter show];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
